package com.gzc.util;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.ValueFilter;


public class JsonUtil {

	/**
	 * json转换成对应的bean对象
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static <T> T json2Bean(String json, Class<T> clazz) {
		if (json!=null && !"".equals(json)) {
			try {
				return JSON.parseObject(json, clazz);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * bean对象转换成json
	 * @param obj
	 * @return
	 */
	public static String bean2JSON(Object obj) {
		String json = "";
		ValueFilter filter = new ValueFilter() {
			@Override
			public Object process(Object source, String name, Object value) {
				if (value == null) {
					return "";
				}
				return value;
			}
		};
		try {
			SerializeWriter out = new SerializeWriter();
			JSONSerializer serializer = new JSONSerializer(out);
			serializer.getValueFilters().add(filter);
			serializer.write(obj);
			json = out.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}
	
	/**
	 * json转换成对应的List对象
	 * @param json 
	 * <p>json格式： [{"arrtibute":28,"id":"L0000002","sort":5},{"arrtibute":28,"id":"L0000012","sort":9}]
	 * @param clazz
	 * @return
	 */
	public static <T> List<T> json2List(String json, Class<T> clazz) {
		if (json!=null && !"".equals(json)) {
			try {
				return JSON.parseArray(json, clazz);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
